package com.ge.energy.pgs.myfleet.code.servlet.websocket;

import java.io.IOException;
import org.eclipse.jetty.websocket.WebSocket.OnTextMessage;

import com.ge.energy.pgs.myfleet.code.factory.BedoFunctionFactory;
import com.ge.energy.pgs.myfleet.code.factory.MyServletFactory;
import com.ge.energy.pgs.myfleet.code.user.BedoFinalImpl;

import com.ge.energy.pgs.myfleet.code.user.Register;


import com.ge.energy.pgs.myfleet.code.vo.WebMessage;
import com.ge.energy.pgs.myfleet.database.data.DataInitBean;
import com.google.gson.Gson;



public class MyWebSocket  implements OnTextMessage {

	private Connection conn;
	private String userId;
	private String password;
	private String requestStr;
	private Gson gson = new Gson();

	public MyWebSocket(String user1d,String pa55word,String requestStr){
		this.userId = user1d;
		this.password = pa55word;
		this.requestStr = requestStr;
	}

	@Override
	public void onClose(int arg0, String arg1) {
		
		
		if(BedoFunctionFactory.bedofunctions.containsKey(this.userId)){
		
			BedoFunctionFactory.bedofunctions.get(this.userId).close();
			
			BedoFunctionFactory.bedofunctions.remove(this.userId);
		
			System.out.println("onClose==========================");
		
		}
	}


	@Override
	public void onOpen(Connection conn) {
		//conn.setMaxIdleTime(3600000);
		this.conn = conn;
		this.conn.setMaxIdleTime(3600000);
		System.out.println("onOpen=========================="+ this.conn.getMaxIdleTime());

		if(DataInitBean.id$password.containsKey(this.userId)){
			if(DataInitBean.id$password.get(this.userId).equals(this.password)){
				MyServletFactory.getSockets().put(this.userId, this);
				
				if(!BedoFunctionFactory.bedofunctions.containsKey(this.userId)){
					BedoFunctionFactory.bedofunctions.put(this.userId, new BedoFinalImpl());
				}

			}else{
				try {
					this.getConn().sendMessage("{\"flag\":\"$client_login\",\"status\":\"用户名或密码错误！\",\"backvalue\":\"\"}");
				} catch (IOException e) {
					e.printStackTrace();
				}
				this.conn.disconnect();
			}
		}
		
	}


	@Override
	public void onMessage(String data) {
		System.out.println("~~~~~~~~~~" + data);
	
		
		WebMessage message = this.getGson().fromJson(data, WebMessage.class);
		if(message == null)
			return;
		String methodName = message.getFlag();
		String value = message.getValue();
		
		if(methodName != null && value != null){
			
			try {
				BedoFinalImpl uc = BedoFunctionFactory.bedofunctions.get(this.userId);	
				BedoFinalImpl.class.getMethod(methodName, String.class).invoke(uc, value);
			} catch (Exception e) {
				e.printStackTrace();
			} 

		}

	}

	public synchronized Connection getConn() {
		return conn;
	}

	public void setConn(Connection conn) {
		this.conn = conn;
	}

	public synchronized Gson getGson() {
		return gson;
	}

	public void setGson(Gson gson) {
		this.gson = gson;
	}
	
}

